# write by hasaki
# first edit on 2019/03/24
# last change on 2019/05/28
# gateio交易所的行情websoket接口，自带测试
# API文档：https://gateio.org/docs/futures/ws/index.html#cancel-subscription-10

import os
import sys
import hmac
import hashlib
import time
import json
from datetime import datetime

from websocket import create_connection

class GateWebsocket:
    def __init__(self):
        '''gateio的websocket接口'''
        self.ws=None                                      # socket对象
        self.baseUrl='wss://fx-ws.gateio.ws/v4/ws'        # 基础链接
        self.api_key=''                                   # 交易所的api
        self.screte_key=''                                # 交易所账户的密钥
        self.signature=None                               # 签名变量
    
    # --------------------------------------------------------------
    # 设置相关
    def setting(self,api_key,screte_key):
        '''外部传进来的设置参数'''
        self.api_key=api_key
        self.screte_key=screte_key
    
    def makeHash(self):
        '''用于交易所那边的鉴权'''
        message = 'channel={}&event={}&time={}'.format('futures.orders', 'subscribe', int(time.time()))
        self.signature=hmac.new(self.screte_key, message, hashlib.sha512).hexdigest()

    # --------------------------------------------------------------
    # 行情数据
    def futuresTick(self,contract):
        '''订阅期货tick行情,contract="BTC_USD" '''
        data={"time" : 123456, "channel" : "futures.tickers", "event": "subscribe", "payload" : ["BTC_USD"]}
        data_str=json.dumps(data)
        self.ws.send(data_str)
    
    def futuresTrade(self,contract):
        '''返回成交数据,contract="BTC_USD" '''
        data={"time" : 123456, "channel" : "futures.trades", "event": "subscribe", "payload" : ["BTC_USD"]}
        data_str=json.dumps(data)
        self.ws.send(data_str)
    
    def futuresDepth(self,contract,num):
        '''订阅深度数据,contract="BTC_USD", num="20", "0" '''
        data={"time" : 123456, "channel" : "futures.order_book", "event": "subscribe", "payload" : ["BTC_USD", "20", "0"]}
        data_str=json.dumps(data)
        self.ws.send(data_str)
    
    def futuresKline(self,contract,frequancy):
        '''获取K线，contract='BTC_USD',frequancy='1m' 
        {"time":1553688363,"channel":"futures.candlesticks","event":"update","error":null,"result":[{"t":1553688360,"c":"4.067","h":"4.067","l":"4.067","o":"4.067","n":"1m_EOS_USD"}]}'''
        data={"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : [frequancy, contract]}
        data_str=json.dumps(data)
        self.ws.send(data_str)

    def futuresOrders(self,contract,payload):
        '''委托推送contract='BTC_USD',payload='20011' '''
        data={
            "time" : 123456,
            "channel" : "futures.orders",
            "event": "subscribe",
            "payload" : [payload, contract],
            "auth": {
                "method": "api_key",
                "KEY":self.api_key,
                "SIGN": self.signature
                }}
        data_str=json.dumps(data)
        self.ws.send(data_str)
    
    def futuresBalances(self):
        '''账户余额'''
        data={
        "time" : 123456,
        "channel" : "futures.balances",
        "event": "subscribe",
        "payload" : ["20011"],
        "auth": {
            "method": "api_key",
            "KEY":self.api_key,
            "SIGN":self.signature
        }}
        data_str=json.dumps(data)
        self.ws.send(data_str)
        
    # --------------------------------------------------------------
    # 启动函数
    def start(self):
        #self.makeHash()
        self.ws=create_connection(self.baseUrl)
    
    def stop(self):
        self.ws.close()
    
    def reconnect(self):
        '''重连'''
        self.stop()
        self.start()
    
    def run(self):
        return self.ws.recv()
    
    def test(self):
        '''测试用的函数'''
        self.api_key=''
        self.screte_key=''
        #self.makeHash()
        self.ws=create_connection(self.baseUrl)
        data={"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["1h", "EOS_USD"]}
        data_str=json.dumps(data)
        data1={"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["1m", "EOS_USD"]}
        data_str1=json.dumps(data1)
        self.ws.send(data_str)
        self.ws.send(data_str1)
        while 1:
            print(self.ws.recv())


if __name__=='__main__':
    test=GateWebsocket()
    test.test()
    